<template>
  <panelHead :route="route"/>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="12" v-for="chart in chartConfigs" :key="chart.title">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <span>{{ chart.title }} 数据表</span>
            <el-radio-group v-model="chart.mode" size="small" @change="() => fetchData(chart)">
              <el-radio-button label="realtime">实时</el-radio-button>
              <el-radio-button label="history">历史</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="chart.ref" :id="chart.ref" class="chart-box"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { onMounted, reactive, nextTick } from 'vue';
import * as echarts from 'echarts';
import { waterQualityService } from '@/api/waterQuality.js';
import { useRoute } from 'vue-router'
const route = useRoute()
//const chartData = ref([]);  // 用于存储后端返回的数据
const chartConfigs = reactive([
  {
    title: '水温',
    table: '1_water_temperature',
    column: 'temperature',
    mode: 'realtime',
    ref: 'chart1',
    chartInstance: null,
    yUnit: '℃',
    min:15,
    max:25,
    markLine: [18, 23],
    colorGradient: ['#FFCCCC', '#FF9999', '#FF6666', '#FF0000', '#CC0000'] // 淡红 → 深红
  },
  {
    title: '溶解氧',
    table: '2_dissolved_oxygen',
    column: 'dissolved_oxygen',
    mode: 'realtime',
    ref: 'chart2',
    chartInstance: null,
    yUnit: 'mg/L',
    min:6,
    max:8,
    markLine: [6.5, 7.5],
    colorGradient: ['#CCF2FF', '#99E6FF', '#66D9FF', '#33CCFF', '#0099CC'] // 淡蓝 → 深蓝
  },
  {
    title: 'pH 值',
    table: '3_ph_value',
    column: 'ph',
    mode: 'realtime',
    ref: 'chart3',
    chartInstance: null,
    yUnit: 'pH',
    min:6,
    max:8,
    markLine: [6.8, 7.8],

    colorGradient: ['#FFCCE5', '#FF99CC', '#CC99FF', '#9966CC', '#663399'] // 淡粉 → 紫色
  }
]);

const fetchData = async (chart) => {
  const apiFunc = chart.mode === 'realtime'
    ? waterQualityService.getRealtimeData
    : waterQualityService.getHistoryData;

  try {
    const response = await apiFunc(chart.table);
    const data = Array.isArray(response.data) ? response.data : response.data.data;
    console.log(data,"data")
    await nextTick();

    if (!chart.chartInstance) {
      const dom = document.getElementById(chart.ref);
      if (!dom) return console.error(`未找到 DOM 元素: ${chart.ref}`);
      chart.chartInstance = echarts.init(dom);
    }

    chart.chartInstance.setOption({
      title: {
        text: `${chart.title} - ${chart.mode === 'realtime' ? '最近24小时' : '最近30天'}`,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '10%', right: '10%', bottom: '18%'
      },
      xAxis: {
        type: 'category',
        name: '时间',
        nameLocation: 'end',
        nameGap: 30,
        nameTextStyle: {
          align: 'right',         // 右对齐
          padding: [0, 0, 0, 0],  // 可根据实际再调
          fontWeight: 'bold'
        },
        axisLine: {
          onZero: false
        },
        data: data.map(item => item.time)
      },
      yAxis: {
        type: 'value',
        name: `${chart.title} (${chart.yUnit})`,
        nameLocation: 'end',
        nameGap: 20,
        min: `${chart.min}`,
        max: `${chart.max}`
      },
      toolbox: {
        right: 10,
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
            title: {
              zoom: '区域缩放',
              back: '缩放还原'
            }
          },
          restore: {
            title: '还原'
          },
          saveAsImage: {
            title: '保存为图片'
          }
        }
      },
      dataZoom: [
        { startValue: 0 },
        { type: 'inside' }
      ],
      visualMap: {
        top: '6%',
        right: '1%',
        min: chart.min,
        max: chart.max,
        calculable: true,
        realtime:true,
        //inRange: {
        //pieces: chart.visualPieces,
        text:[`${chart.max}${chart.yUnit}`, `${chart.min}${chart.yUnit}`],   
        inRange: {
          color: chart.colorGradient  // 这里引用每个 chart 的颜色数组
        },
        outOfRange: {
          color: '#999'
        }
      },
      series: [
        {
          name: chart.title,
          type: 'line',
          smooth: true,
          data: data.map(item => item.value),
          markLine: {
            silent: true,
            data: chart.markLine.map((y, i) => ({
              yAxis: y,
              lineStyle: {
                color: i === 0
                  ? chart.colorGradient[1]     // 第一条线使用第一个颜色
                  : chart.colorGradient.at(-2) // 第二条线使用最后一个颜色
              }
            }))
          }
        }
      ]
    });
    setTimeout(() => {
      chart.chartInstance.resize({
        width: dom.offsetWidth
      });
    }, 50);
  }catch (error) {
    console.error('图表数据加载失败:', error);
  }
};
onMounted(() => {
  chartConfigs.forEach(chart => fetchData(chart));
});
</script>

<style scoped>
.dashboard {
  padding: 20px;
}
.chart-card {
  margin-bottom: 20px;
}
.chart-box {
  width: 100%;
  height: 400px;
  box-sizing: border-box; 
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

</style>
